package com.ming.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.ming.model.SmsModel;
import com.rabbitmq.client.Channel;
import com.ming.constant.QueueConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



/**
 * @Author:何元才
 * @Desc: 监听短信消息
 *        真正的发短信
 * @data:2021-04-07 14:55
 */
@Component
@Slf4j
public class SmsListener {

    @Autowired
    private IAcsClient acsClient;

    /**
     * 流程member --------- mq --------->message监听处理
     * 这个方法是监听短信消息的
     * 这里真正发短信
     * @param message
     * @param channel
     */
    @RabbitListener(queues = QueueConstant.PHONE_SMS_QUEUE, concurrency = "3-5")
    public void  smsHandler(Message message , Channel channel){
        //1.拿到消息
        String msgStr = new String(message.getBody());
        JSONObject jsonObject = JSON.parseObject(msgStr);
        //2.拿到id
        String userId = jsonObject.getString("userId");
        //3.拿到消息对象
        SmsModel smsModel = jsonObject.getObject("smsModel", SmsModel.class);
        //真正发短信的方法
        try {
            realSendMsg(smsModel);
            //成功了 记录数据
            //记录数据 sms_log

            //签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            log.error("发送短信失败");
        }
    }

    /**
     * 发短信的方法
     *
     * @param smsModel
     */
    private String realSendMsg(SmsModel smsModel) {
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
        request.setPhoneNumbers(smsModel.getPhoneNumbers());
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(smsModel.getSignName());
        //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
        request.setTemplateCode(smsModel.getTemplateCode());
        request.setTemplateParam(smsModel.getTemplateParam());
        try {
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            System.out.println(sendSmsResponse.getCode());
        } catch (ClientException e) {
            log.error("发送失败");
        }
        return "发送失败";
    }
}
